import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_learn_vi/src/bean/bean_video.dart';
import 'package:flutter_learn_vi/src/net/dio_utils.dart';
import 'package:flutter_learn_vi/src/page/common/common_loading_dialog.dart';
import 'package:flutter_learn_vi/src/page/common/common_nodata_widget.dart';
import 'package:flutter_learn_vi/src/page/study/course/video_details2_widget.dart';
import 'package:flutter_learn_vi/src/page/study/course/video_details_code_link_page.dart';
import 'package:flutter_learn_vi/src/utils/log_util.dart';
import 'package:flutter_learn_vi/src/utils/navigator_utils.dart';
import 'package:get/get.dart';
import 'package:video_player/video_player.dart';
import 'package:wakelock/wakelock.dart';

import '../../../bean/bean_integral.dart';
import '../../../bean/bean_train.dart';
import '../../../bean/bean_user_account.dart';
import '../../../utils/toast_utils.dart';
import '../controller/course_video_details_controller.dart';
import 'course_http_model.dart';
import 'course_ppt_details_page.dart';

/// 创建人： Created by zhaolong
/// 创建时间：Created by  on 2021/1/13.
///
/// 可关注公众号：我的大前端生涯   获取最新技术分享
/// 可关注网易云课堂：https://study.163.com/instructor/1021406098.htm
/// 可关注博客：https://blog.csdn.net/zl18603543572
///
/// 代码清单
///代码清单
class CourseVideoDetailsPage extends StatefulWidget {
  final int videoIndex;

  ///课程Id
  final int videoCourseId;

  ///视频ID
  final int videoId;

  ///培训入口进入
  final int trainId;

  ///任务入口
  final int taskId;

  final String pageTag;

  const CourseVideoDetailsPage({
    Key key,
    this.videoIndex = 0,
    this.trainId,
    this.taskId,
    this.pageTag = '',
    @required this.videoCourseId,
    this.videoId,
  }) : super(key: key);

  @override
  _CourseVideoDetailsPageState createState() => _CourseVideoDetailsPageState();
}

class _CourseVideoDetailsPageState extends State<CourseVideoDetailsPage>
    with CourseHttpModel {
  //创建一个多订阅流
  StreamController<VideoPlayerController> _streamController =
      StreamController.broadcast();
  StreamController<VideoModel> _nextController = StreamController.broadcast();

  int _currentSelectIndex = 0;

  ScrollController _scrollController = new ScrollController();

  CourseVideoDetailsController _courseVideoDetailsController;

  @override
  void initState() {
    super.initState();

    debugPrint("课程详情页面 ${widget.pageTag}");
    //使用
    Wakelock.enable();

    _courseVideoDetailsController = Get.put(
        CourseVideoDetailsController(widget.trainId),
        tag: "${widget.videoCourseId}");
    _currentSelectIndex = widget.videoIndex;
    _getCourseVideoList();
  }

  @override
  void dispose() {
    //不在使用
    Wakelock.disable();
    _nextController.close();
    _streamController.close();
    if (autoProgressTimer != null) {
      autoProgressTimer.cancel();
      autoProgressTimer = null;
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        _courseVideoDetailsController.closePage();
        return true;
      },
      child: Scaffold(
        appBar: AppBar(
          leading: BackButton(
            onPressed: () {
              _courseVideoDetailsController.closePage();
            },
          ),
          title: Text("课程学习"),
        ),
        backgroundColor: Colors.white,

        ///填充布局
        body: Container(
            width: double.infinity,
            height: double.infinity,
            child: SingleChildScrollView(child: buildColumn())),
      ),
    );
  }

  Widget buildColumn() {
    if (_isLoading) {
      return LoadingWidget();
    }
    if (_videoModelList == null || _videoModelList.length == 0) {
      return NoDataWidget(
        text: "暂无数据",
      );
    }

    return Column(
      children: [
        buildVideoContainer(),
        Container(
          height: 100,
          margin: EdgeInsets.only(left: 14, top: 20),
          child: buildCourseListFunction(),
        ),
        buildVideoInfoContainer(),
      ],
    );
  }

  Container buildVideoContainer() {
    VideoModel videoModel = _videoModelList[_currentSelectIndex];
    //课件类型 0 视频 1 PPT 2  视频代码连接
    int videoTypes = videoModel.videoTypes;
    if (videoTypes == 1 || videoTypes == 2) {
      return Container(
        height: 0,
      );
    }

    return Container(
      height: 240,
      child: StreamBuilder<VideoModel>(
        stream: _nextController.stream,
        initialData: _videoModelList[_currentSelectIndex],
        builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
          VideoModel event = snapshot.data;
          return VideoDetailsWidget(
            trainId: widget.trainId,
            trainBean: _trainBean,
            integralStatBean: _rankStatBean,
            taskBean: _taskBean,
            init: event,
            key: ValueKey("$_currentSelectIndex"),
          );
        },
      ),
    );
  }

  buildCourseListFunction() {
    return GetBuilder(
      id: "videoListId",
      tag: "${widget.videoCourseId}",
      builder: (CourseVideoDetailsController controller) {
        LogUtils.e("视频播放 GetBuilder 执行更新");
        return ListView.builder(
          controller: _scrollController,
          scrollDirection: Axis.horizontal,
          itemCount: _videoModelList.length,
          itemBuilder: (BuildContext context, int index) {
            bool isPlay = _currentSelectIndex == index;
            return InkWell(
              onTap: () {
                VideoModel videoModel = _videoModelList[index];
                openPageFunction(videoModel, index);
              },
              child: buildContainer(isPlay, index),
            );
          },
        );
      },
    );
  }

  Container buildContainer(bool isPlay, int index) {
    VideoModel videoModel = _videoModelList[index];
    return Container(
      width: 160,
      margin: EdgeInsets.only(right: 10),
      height: 60,
      decoration: BoxDecoration(
          borderRadius: BorderRadius.all(Radius.circular(4)),
          border: Border.all(
            color: Colors.green,
            width: 1.0,
          )),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Container(
                margin: EdgeInsets.only(top: 0, left: 1),
                padding: EdgeInsets.only(left: 2, right: 2, top: 1, bottom: 1),
                child: Text(
                  buildPlayFlagText(videoModel, isPlay),
                  style: TextStyle(color: Colors.white, fontSize: 10),
                ),
                color: isPlay ? Colors.green : Colors.blueGrey,
              ),
              buildRightProgressText(videoModel),
            ],
          ),
          Container(
            padding: EdgeInsets.all(10),
            child: Text(
              "${index + 1} ${videoModel.videoName}",
              maxLines: 2,
              overflow: TextOverflow.ellipsis,
              style: TextStyle(
                fontSize: 14,
                color: isPlay ? Colors.green : Colors.blueGrey,
              ),
            ),
          ),
        ],
      ),
    );
  }

  List<VideoModel> _videoModelList;
  bool _isLoading = true;
  IntegralStatBean _rankStatBean;
  TaskBean _taskBean;
  int _taskId;
  TrainBean _trainBean;
  Timer autoProgressTimer;

  ///定时请求 用来更新目录的视频进度
  void autoUpdateProgressRequest() {
    autoProgressTimer = Timer.periodic(Duration(seconds: 20), (timer) async {
      List<VideoModel> themList = await getVideoList(
          videoCourseId: widget.videoCourseId, trainId: widget.trainId);
      for (int i = 0; i < _videoModelList.length; i++) {
        VideoModel model = _videoModelList[i];
        for (int k = 0; k < themList.length; k++) {
          VideoModel model2 = themList[i];
          if (model2.id == model.id) {
            _videoModelList[i].videoSecond = model2.videoSecond;
            _videoModelList[i].finishPercent = model2.finishPercent;
            break;
          }
        }
      }
      _courseVideoDetailsController.update(["videoListId"]);
    });
  }

  ///获取课程视频详情
  void _getCourseVideoList() async {
    _taskId = widget.taskId;
    if (_taskId == null) {
      LogUtils.e("加载请求默认的任务配置 start ");
      ResponseInfo taskConfigResponse = await DioUtils.instance.getRequest(
        url: HttpHelper.taskVideoDefaultConfig,
      );
      if (taskConfigResponse.success) {
        LogUtils.e("加载请求默认的任务配置 success ");
        var responseData = taskConfigResponse.data;
        if (responseData != null) {
          TaskBean taskBean = TaskBean.fromMap(responseData);
          _taskId = taskBean.id;
          LogUtils.e("加载请求默认的任务配置 默认的配置  $_taskId");
        } else {
          LogUtils.e("加载请求默认的任务配置 无默认的配置 ");
        }
      } else {
        LogUtils.e("加载请求默认的任务配置 失败 ");
      }
    }

    if (_taskId == null) {
      //获取积分配置
      ResponseInfo statisRresponseInfo = await DioUtils.instance.getRequest(
        url: HttpHelper.integralStatisticsVideo,
      );
      if (statisRresponseInfo.success) {
        var responseData = statisRresponseInfo.data;
        if (responseData != null) {
          _rankStatBean = IntegralStatBean.fromJson(responseData);
        }
      }
    } else {
      //获取任务配置
      Map<String, dynamic> queryParameters = Map();
      //任务类型 0 阅读 ； 1 学习；2 看视频
      queryParameters["taskFlag"] = 2;
      queryParameters["taskId"] = _taskId;

      //检查任务完成度
      //校验积分
      ResponseInfo checkResponsseInfo = await DioUtils.instance.getRequest(
        url: HttpHelper.taskConfigCheck,
        queryParameters: queryParameters,
      );
      if (checkResponsseInfo.success) {
        //可以完成积分 获取积分详情
        ResponseInfo taskConfigResponse = await DioUtils.instance.getRequest(
          url: HttpHelper.taskConfig,
          queryParameters: queryParameters,
        );
        if (taskConfigResponse.success) {
          //获取积分详情成功
          var responseData = taskConfigResponse.data;
          if (responseData != null) {
            _taskBean = TaskBean.fromMap(responseData);
            _rankStatBean = _taskBean.examinConfig;
          } else {
            //未获取到积分数据
          }
        }
      } else {
        LogUtils.e("${checkResponsseInfo.message}");
      }
    }

    //培训相关
    if (widget.trainId != null) {
      debugPrint("课程学习页面 开始获取培训信息");
      Map<String, dynamic> monthMap = {
        "trainId": widget.trainId,
      };
      //获取培训的信息
      ResponseInfo statisRresponseInfo = await DioUtils.instance.postRequest(
        url: HttpHelper.trainDetailsInfo,
        jsonMap: monthMap,
        encrypt: true,
      );
      _isLoading = false;
      if (statisRresponseInfo.success) {
        if (statisRresponseInfo.data != null) {
          _trainBean = TrainBean.fromJson(statisRresponseInfo.data);
          debugPrint("课程学习页面 获取培训信息成功");
        } else {
          debugPrint("课程学习页面 获取培训信息失败");
        }
      }
    } else {
      debugPrint("课程学习页面 widget.trainId  is null ");
    }

    await requestVideoList();
    _isLoading = false;
    if (widget.videoId != null) {
      for (int i = 0; i < _videoModelList.length; i++) {
        VideoModel model = _videoModelList[i];
        if (model.id == widget.videoId) {
          _currentSelectIndex = i;
          //课件类型 0 视频 1 PPT
          int videoTypes = model.videoTypes;
          if (mounted) {
            setState(() {});
          }

          await Future.delayed(Duration(milliseconds: 500));
          openPageFunction(model, _currentSelectIndex);
          await Future.delayed(Duration(milliseconds: 500));
          if (widget.videoIndex > 1) {
            if (_scrollController.hasClients) {
              _scrollController.animateTo(widget.videoIndex * 160 * 1.0,
                  duration: Duration(milliseconds: 400), curve: Curves.linear);
            }
          }
          break;
        }
      }
    } else {
      if (_videoModelList.length == 1) {
        VideoModel videoModel = _videoModelList[_currentSelectIndex];
        //课件类型 0 视频 1 PPT
        int videoTypes = videoModel.videoTypes;
        if (videoTypes == 1) {
          NavigatorUtils.pushPage(
              context,
              PPTDetailsPage(
                key: UniqueKey(),
                trainBean: _trainBean,
                trainId: widget.trainId,
                videoModel: videoModel,
              ),
              isReplace: true);
          return;
        }
      }
    }
    if (mounted) {
      setState(() {});
    }

    ///开启定时任务
    //autoUpdateProgressRequest();
  }

  Future<bool> requestVideoList() async {
    _videoModelList = await getVideoList(
        videoCourseId: widget.videoCourseId, trainId: widget.trainId);
    return true;
  }

  Widget buildRightProgressText(VideoModel model) {
    int userStatues = model.userStatues;
    String finishPercent = model.finishPercent;
    String leftText = "";
    Color textColor = Colors.grey;
    if (userStatues == -1) {
      leftText = "";
      textColor = Colors.grey;
    } else if (userStatues == 1) {
      leftText = "进行中  $finishPercent";
      textColor = Colors.blue;
    } else if (userStatues == 2) {
      leftText = "已完成";
      textColor = Colors.green;
    }
    return Row(
      children: [
        Container(
          margin: EdgeInsets.only(left: 8),
          child: Text(
            leftText,
            style: TextStyle(fontSize: 12, color: textColor),
          ),
        ),
      ],
    );
  }

  String buildPlayFlagText(VideoModel videoModel, bool isPlay) {
    //课件类型 0 视频 1 PPT
    int videoTypes = videoModel.videoTypes ?? 0;
    if (videoTypes == 0) {
      return isPlay ? "点击播放" : "视频";
    } else if (videoTypes == 2) {
      return isPlay ? "点击播放" : "视频";
    } else if (videoTypes == 1) {
      return "PPT";
    } else {
      return "其他";
    }
  }

  openPageFunction(VideoModel videoModel, int index) async {
    //课件类型 0 视频 1 PPT 2 代码链接
    int videoTypes = videoModel.videoTypes ?? 0;
    _currentSelectIndex = index;
    if (videoTypes == 0) {
      await _courseVideoDetailsController.changPlayVideo();
      _nextController.add(_videoModelList[index]);
      _scrollController.animateTo(index * 160 * 1.0,
          duration: Duration(milliseconds: 400), curve: Curves.linear);
      addIntegral(videoModel);
    } else if (videoTypes == 1) {
      await Get.to(
        () => PPTDetailsPage(
          key: UniqueKey(),
          trainId: widget.trainId,
          trainBean: _trainBean,
          videoModel: videoModel,
        ),
      );
      await requestVideoList();
    } else if (videoTypes == 2) {
      await Get.to(
        () => VideoDetailsCodeLinkPage(
          trainBean: _trainBean,
          trainId: widget.trainId,
          videoModel: videoModel,
          integralStatBean: _rankStatBean,
          key: UniqueKey(),
        ),
      );
      await requestVideoList();
    } else {
      ToastUtils.showToast("本版本暂不支持查看");
    }

    setState(() {});
  }

  buildVideoInfoContainer() {
    return Container(
      padding: EdgeInsets.all(12),
      width: double.infinity,
      margin: EdgeInsets.only(top: 20),
      child: StreamBuilder<VideoModel>(
        stream: _nextController.stream,
        initialData: _videoModelList[_currentSelectIndex],
        builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
          VideoModel videoModel = snapshot.data;
          String videoInfo = videoModel.videoInfo;

          if (videoInfo.isEmpty) {
            return SizedBox();
          }
          return Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            children: [
              Container(
                margin: EdgeInsets.only(bottom: 12),
                child: Text(
                  "视频简介",
                  style: TextStyle(fontWeight: FontWeight.bold),
                ),
              ),
              Container(
                child: Text(videoInfo),
              )
            ],
          );
        },
      ),
    );
  }

  Future<bool> addIntegral(VideoModel videoModel) async {
    Map<String, dynamic> map = {
      "desId": videoModel.id,
      "taskType": 5,
    };
    map["newsTitle"] = videoModel.videoName;

    ResponseInfo partResponseInfo = await DioUtils.instance.postRequest(
      url: HttpHelper.addNewsIntegarlUrl,
      jsonMap: map,
    );
    if (partResponseInfo.success) {
      LogUtils.e("积分添加成功");
    } else {
      LogUtils.e("积分添加失败");
    }

    return Future.value(true);
  }
}
